package utils.database;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import objects.Skill_information;

public class Connection {

	public static String get_skill_from_database(Long skillid) { 
		String adresse = "http://192.168.1.1:8080/swtor_database/json_skill/"+skillid;
		String toreturn = null;
		  try { 
//		creation d'un objet URL 
		    URL url = new URL(adresse); 
//		on etablie une connection a cette url 
		   URLConnection uc = url.openConnection(); 
//		on y cree un flux de lecture 
		   InputStreamReader in = new InputStreamReader(uc.getInputStream(), "UTF-8"); 
//		on lit le premier bit 
		   int c = in.read(); 
//		on cree un StringBuilder pour par la suite y ajouter tout les bit lus 
		   StringBuilder build = new StringBuilder(); 
//		tant que c n'est pas egale au bit indiquant la fin d'un flux... 
		   while (c != -1) { 
		    build.append((char) c); 
//		...on l'ajoute dasn le StringBuilder... 
		    c = in.read(); 
//		...on lit le suivant 
		   } 
//		on retourne le code de la page 
		   toreturn = build.toString(); 
		   
		  } catch (MalformedURLException e) { 
			  System.out.println(adresse);
		   e.printStackTrace(); 
		  } catch (IOException e) { 
			  System.out.println(adresse);
		   e.printStackTrace(); 
		  }
		   return toreturn;
		 } 
	public static String post_skill_to_database(Skill_information info) {
		return null;
	}
	JSONObject obj=new JSONObject();
    JSONObject codes=new JSONObject();
    //Forms the name value pairs for the barcodes and quantity
    codes.put("598013", new Integer(10));
    codes.put("5849632927",new Integer(15));
    codes.put ("5849676037",new Integer(20));
    codes.put ("6634391931", new Integer(25));

    //Headers in the JSON array
    obj.put("LoginID", new Integer(1234));
    obj.put("Machine_ID", new Integer(123456789));
    obj.put("add", codes);
    System.out.print(obj);

    //httppost
    try {
        HttpClient httpclient= new DefaultHttpClient();
        HttpResponse response;
        HttpPost httppost= new HttpPost ("http://example/receive.php");
        StringEntity se=new StringEntity ("myjson: "+obj.toString());
        httppost.setEntity(se);
        System.out.print(se);
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-type", "application/json");

        response=httpclient.execute(httppost);

    }
    catch (Exception e) {
        e.printStackTrace();
        System.out.print("Cannot establish connection!");
    }
}
}
